#!/bin/sh
#
# $FreeBSD$
#

# PROVIDE: ix-bsdloader
# BEFORE: middlewared earlykld

. /etc/rc.freenas

migrate_bsd_loader()
{
	kenv -q grub.platform >/dev/null
	if [ $? -ne 0 ] ; then
		# Nothing to do
		return 0
	fi

	#echo "Removing GRUB dataset"
	#zfs destroy -R -f freenas-boot/grub

	# Thow the new boot-loader on each disk
        for disk in $(sysctl -n kern.disks); do

		# Why CD's show up in kern.disks? Dunno...
		echo $disk | grep -q "^cd[0-9]"
		if [ $? -eq 0 ] ; then continue ; fi

		# Check if the disk has a gptid on the second "p2" partition
		gptid=$(gpart list $disk | grep rawuuid | sed -n 2p | awk '{print $2}')
		# If we didn't find a gptid for this disk / partition, set to a bogus name so we dont match
		if [ -z "$gptid" ] ; then gptid="bogusdisknamenotused" ; fi

		# Does this disk exist in freenas-boot?
		/usr/local/sbin/zpool status freenas-boot | grep -q -e " ${disk}p2 " -e " gptid/$gptid "
		if [ $? -ne 0 ] ; then continue ; fi

        	if gpart show ${disk} | grep -q bios-boot; then
			gpart modify -i 1 -t freebsd-boot /dev/${disk}
			gpart bootcode -b /boot/pmbr -p /boot/gptzfsboot -i 1 /dev/${disk}
		elif gpart show ${disk} | grep -q " efi "; then
			if mount -t msdosfs /dev/${disk}p1 /boot/efi; then
				cp /boot/boot1.efi /boot/efi/efi/boot/BOOTx64.efi
				umount -f /boot/efi
	                fi
		fi
	done

	# Cleanup current BE environment
	ed /conf/base/etc/fstab << EOF
g#^freenas-boot/grub#d
w
q
EOF
}

name="ix-bsdloader"
start_cmd='migrate_bsd_loader'
stop_cmd=':'

load_rc_config $name
run_rc_command "$1"
